package com.x.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * .
 *
 * @author o_o
 * @date 2024-06-08
 */
@Slf4j
@Data
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {

    private final CopyOnWriteArraySet<WebSocketServer> websocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    /**
     * 建立连接成功调用的方法.
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        websocketSet.add(this);
        log.info("{} 连接建立成功， 当前人数：{}", session, websocketSet.size());
    }

    /**
     * 连接关闭调用的方法.
     */
    @OnClose
    public void onClose() throws IOException {
        session.close();
        websocketSet.remove(this);
        log.info("{} 连接断开， 当前人数：{}", session, websocketSet.size());
    }

    /**
     * .
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自: {} 的消息：{}", session, message);
    }

    @OnError
    public void onError(Session session, Throwable exception) {
        log.error("onError");
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 向所有客户端推送消息.
     *
     * @param message
     * @throws IOException
     */
    public void push2AllClient(String message) throws IOException {
        for (WebSocketServer server : websocketSet) {
            log.info("push {} to {}", message, this.session);
            server.session.getBasicRemote().sendText(message);
        }
    }
}
